/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package kimo.persistence.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import kimo.persistence.entities.ProductCategory;
import kimo.persistence.entities.Product;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import kimo.persistence.controllers.exceptions.IllegalOrphanException;
import kimo.persistence.controllers.exceptions.NonexistentEntityException;
import kimo.persistence.entities.ProductType;

/**
 *
 * @author a381u296
 */
public class ProductTypeJpaController implements Serializable {

    public ProductTypeJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(ProductType productType) {
        if (productType.getProductList() == null) {
            productType.setProductList(new ArrayList<Product>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ProductCategory productTypeCategoryId = productType.getProductTypeCategoryId();
            if (productTypeCategoryId != null) {
                productTypeCategoryId = em.getReference(productTypeCategoryId.getClass(), productTypeCategoryId.getProductCategoryId());
                productType.setProductTypeCategoryId(productTypeCategoryId);
            }
            List<Product> attachedProductList = new ArrayList<Product>();
            for (Product productListProductToAttach : productType.getProductList()) {
                productListProductToAttach = em.getReference(productListProductToAttach.getClass(), productListProductToAttach.getProductId());
                attachedProductList.add(productListProductToAttach);
            }
            productType.setProductList(attachedProductList);
            em.persist(productType);
            if (productTypeCategoryId != null) {
                productTypeCategoryId.getProductTypeList().add(productType);
                productTypeCategoryId = em.merge(productTypeCategoryId);
            }
            for (Product productListProduct : productType.getProductList()) {
                ProductType oldProductTypeIdOfProductListProduct = productListProduct.getProductTypeId();
                productListProduct.setProductTypeId(productType);
                productListProduct = em.merge(productListProduct);
                if (oldProductTypeIdOfProductListProduct != null) {
                    oldProductTypeIdOfProductListProduct.getProductList().remove(productListProduct);
                    oldProductTypeIdOfProductListProduct = em.merge(oldProductTypeIdOfProductListProduct);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(ProductType productType) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ProductType persistentProductType = em.find(ProductType.class, productType.getProductTypeId());
            ProductCategory productTypeCategoryIdOld = persistentProductType.getProductTypeCategoryId();
            ProductCategory productTypeCategoryIdNew = productType.getProductTypeCategoryId();
            List<Product> productListOld = persistentProductType.getProductList();
            List<Product> productListNew = productType.getProductList();
            List<String> illegalOrphanMessages = null;
            for (Product productListOldProduct : productListOld) {
                if (!productListNew.contains(productListOldProduct)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Product " + productListOldProduct + " since its productTypeId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (productTypeCategoryIdNew != null) {
                productTypeCategoryIdNew = em.getReference(productTypeCategoryIdNew.getClass(), productTypeCategoryIdNew.getProductCategoryId());
                productType.setProductTypeCategoryId(productTypeCategoryIdNew);
            }
            List<Product> attachedProductListNew = new ArrayList<Product>();
            for (Product productListNewProductToAttach : productListNew) {
                productListNewProductToAttach = em.getReference(productListNewProductToAttach.getClass(), productListNewProductToAttach.getProductId());
                attachedProductListNew.add(productListNewProductToAttach);
            }
            productListNew = attachedProductListNew;
            productType.setProductList(productListNew);
            productType = em.merge(productType);
            if (productTypeCategoryIdOld != null && !productTypeCategoryIdOld.equals(productTypeCategoryIdNew)) {
                productTypeCategoryIdOld.getProductTypeList().remove(productType);
                productTypeCategoryIdOld = em.merge(productTypeCategoryIdOld);
            }
            if (productTypeCategoryIdNew != null && !productTypeCategoryIdNew.equals(productTypeCategoryIdOld)) {
                productTypeCategoryIdNew.getProductTypeList().add(productType);
                productTypeCategoryIdNew = em.merge(productTypeCategoryIdNew);
            }
            for (Product productListNewProduct : productListNew) {
                if (!productListOld.contains(productListNewProduct)) {
                    ProductType oldProductTypeIdOfProductListNewProduct = productListNewProduct.getProductTypeId();
                    productListNewProduct.setProductTypeId(productType);
                    productListNewProduct = em.merge(productListNewProduct);
                    if (oldProductTypeIdOfProductListNewProduct != null && !oldProductTypeIdOfProductListNewProduct.equals(productType)) {
                        oldProductTypeIdOfProductListNewProduct.getProductList().remove(productListNewProduct);
                        oldProductTypeIdOfProductListNewProduct = em.merge(oldProductTypeIdOfProductListNewProduct);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = productType.getProductTypeId();
                if (findProductType(id) == null) {
                    throw new NonexistentEntityException("The productType with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ProductType productType;
            try {
                productType = em.getReference(ProductType.class, id);
                productType.getProductTypeId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The productType with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Product> productListOrphanCheck = productType.getProductList();
            for (Product productListOrphanCheckProduct : productListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This ProductType (" + productType + ") cannot be destroyed since the Product " + productListOrphanCheckProduct + " in its productList field has a non-nullable productTypeId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            ProductCategory productTypeCategoryId = productType.getProductTypeCategoryId();
            if (productTypeCategoryId != null) {
                productTypeCategoryId.getProductTypeList().remove(productType);
                productTypeCategoryId = em.merge(productTypeCategoryId);
            }
            em.remove(productType);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<ProductType> findProductTypeEntities() {
        return findProductTypeEntities(true, -1, -1);
    }

    public List<ProductType> findProductTypeEntities(int maxResults, int firstResult) {
        return findProductTypeEntities(false, maxResults, firstResult);
    }

    private List<ProductType> findProductTypeEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(ProductType.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public ProductType findProductType(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(ProductType.class, id);
        } finally {
            em.close();
        }
    }

    public int getProductTypeCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<ProductType> rt = cq.from(ProductType.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
